// src/store/index.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useStore = defineStore('admin', () => {
  // ==================== 核心状态 ====================
  // 1. 认证状态
  const token = ref(localStorage.getItem('admin_token') || '')
  const adminInfo = ref(null) // { id, name, role, permissions }
  const systemLogo = ref(localStorage.getItem('system_logo') || '@/assets/logo.png')
  
  // 2. UI状态
  const isLoading = ref(false)
  const sidebarCollapsed = ref(false)
  
  // 3. 业务数据缓存
  const questionList = ref([]) // 题库列表
  const userList = ref([])     // 用户列表

  // ==================== 计算属性 ====================
  const isLoggedIn = computed(() => !!token.value)
  const isSuperAdmin = computed(() => adminInfo.value?.role === 'super_admin')

  // ==================== 方法 ====================
  // 1. 认证相关
  function login(tokenData, adminData) {
    token.value = tokenData
    adminInfo.value = adminData
    localStorage.setItem('admin_token', tokenData)
  }

  function logout() {
    token.value = ''
    adminInfo.value = null
    localStorage.removeItem('admin_token')
  }

  // 2. UI控制
  function toggleSidebar() {
    sidebarCollapsed.value = !sidebarCollapsed.value
  }



 function updateSystemLogo(newLogo) {
    systemLogo.value = newLogo
    localStorage.setItem('system_logo', newLogo)
  }







  // 3. 数据操作
  async function fetchQuestions() {
    isLoading.value = true
    try {
      // 这里替换为你的实际API调用
      const res = await fetch('/api/questions')
      questionList.value = await res.json()
    } finally {
      isLoading.value = false
    }
  }

  // ==================== 暴露状态和方法 ====================
  return {
    // 状态
    token,
    adminInfo,
    isLoading,
    sidebarCollapsed,
    questionList,
    userList,
    
    // 计算属性
    isLoggedIn,
    isSuperAdmin,
    
    // 方法
    login,
    logout,
    toggleSidebar,
    fetchQuestions,


    systemLogo,
    updateSystemLogo
  }
})
// 在文件最后添加（如果用方案2）
export default useStore